package com.lmm.rsa;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 * * Java调用并执行js文件，传递参数，并活动返回值 * *
 * 
 * @author leiming
 */
public class RSAScriptEngine {
	private static ScriptEngineManager manager = new ScriptEngineManager();
	private static ScriptEngine engine = manager.getEngineByName("javascript");
	static{
		InputStream in  =  RSAScriptEngine.class.getResourceAsStream("/rsa/Barrett.js");
		InputStream in2 = RSAScriptEngine.class.getResourceAsStream("/rsa/BigInt.js");
		InputStream in3 = RSAScriptEngine.class.getResourceAsStream("/rsa/RSA.js");
		try {
			InputStreamReader ir = new InputStreamReader(in, "utf-8");
			InputStreamReader ir2 = new InputStreamReader(in2, "utf-8");
			InputStreamReader ir3 = new InputStreamReader(in3, "utf-8");
			engine.eval(ir);
			engine.eval(ir2);
			engine.eval(ir3);
			
			IOUtils.closeQuietly(ir);
			IOUtils.closeQuietly(ir2);
			IOUtils.closeQuietly(ir3);
		} catch (ScriptException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}finally{
			IOUtils.closeQuietly(in);
			IOUtils.closeQuietly(in2);
			IOUtils.closeQuietly(in3);
		}

	
	}
	public static void main(String[] args) throws Exception {
		
		String modulus = "A6487B5B6F216B74213A9F1AFCADA2BD13716F1ADBF4FE48D76C878DE0C31506B5319499668DFC5919F58255337A396D7156292E6F8D652CBFFA4094446F294AFA12FC2F765A6948ECB2B9C9B656EAED781FD73F538AE0966519F8C187A9A6B5C0A222C2FA4E981CEDD4014C2B65EB7D67CA099076EDCF151809C58008597B7F";
		String publicExponent= "010001";
		String enP = encryptedString(publicExponent, modulus, "abc123");
		System.out.println(enP);
	}
	
	/**
	 * 对密码加密
	 * @param publicExponent
	 * @param modulus
	 * @param password 没有加密的密码
	 * @return
	 */
	public static String encryptedString(String publicExponent,String modulus,String password){
		String encrypteStr = null;
		if (engine instanceof Invocable) {
			Invocable invoke = (Invocable) engine; // 调用setMaxDigits方法，并传入一个参数
			try {
				invoke.invokeFunction("setMaxDigits", 129);
				engine.eval(" var key = new RSAKeyPair('"+publicExponent+"', '','"+modulus+"');");
				Object key = engine.get("key");
				encrypteStr = (String)invoke.invokeFunction("encryptedString", key,password);
			} catch (NoSuchMethodException | ScriptException e1) {
				e1.printStackTrace();
			}
		}
		return encrypteStr;

	}
}